package com.ty.springbootweb.filter;

import com.ty.springbootweb.util.Constants;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * AuthorizationFilter
 *
 * @aurhor Administrator  whs
 * @since 2024/9/6
 */

@WebFilter(filterName = "AuthorizationFilter", urlPatterns = "/*")
public class AuthorizationFilter implements Filter {

    @Override  // 初始化逻辑
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        if (httpRequest.getSession().getAttribute(Constants.login_User) == null) {
            httpResponse.setContentType("text/html;charset=utf-8");
            PrintWriter out = httpResponse.getWriter();
            out.print("<script>alert('请先进行登录，再进行后续操作!(Filter控制)');location.href='" + httpRequest.getContextPath() + "/login.html';</script>");
        } else {
            filterChain.doFilter((ServletRequest) httpRequest, (ServletResponse) httpResponse);
        }
    }

    @Override   // 销毁逻辑
    public void destroy() {
    }
}